#include "SeqList.h"

//初始化
void SeqListInit(SeqList* Sq)
{
    assert(Sq);
    Sq->arr = NULL;
    Sq->capacity = Sq->size = 0;
}

//扩容
static void Expansion(SeqList* Sq)
{
    if(Sq->capacity == Sq->size)
    {
        //扩容
        int newCapacity = Sq->capacity == 0 ? 4 : 2 * Sq->capacity;
        DataType* newArr = (DataType*)realloc(Sq->arr,sizeof(DataType)*newCapacity);
        if(newArr == NULL)
        {
            printf("%s\n",strerror(errno));
            return; 
        }
        Sq->arr = newArr;
        Sq->capacity = newCapacity;
    }
}

//头插
void PushFront(SeqList* Sq,DataType index)
{
    assert(Sq);
    //判断空间是否足够
    Expansion(Sq);
    for(int i = Sq->size;i > 0;i--)
    {
        *(Sq->arr + i) = *(Sq->arr + i - 1);
    }
    *Sq->arr = index;
    Sq->size++;
}

//尾插
void PushBack(SeqList* Sq,DataType index)
{
    assert(Sq);
    //判断空间是否足够
    Expansion(Sq);
    *(Sq->arr + Sq->size) = index;
    Sq->size++;
}

//指定位置插入
void Insert(SeqList* Sq,DataType index,int pos)
{
    assert(Sq && pos >= 0 && pos <= Sq->size);
    //判断空间是否足够
    Expansion(Sq);
    for(int i = Sq->size;i >= pos;i--)
    {
        *(Sq->arr + i) = *(Sq->arr + i - 1);
    }
    *(Sq->arr + pos) = index;
    Sq->size++;
}

//头删
void PopFront(SeqList* Sq)
{
    assert(Sq && Sq->size > 0);
    for(int i = 0;i < Sq->size - 1;i++)
    {
        *(Sq->arr + i) = *(Sq->arr + i + 1);
    }
    Sq->size--;
}

//尾删
void PopBack(SeqList* Sq)
{
    assert(Sq && Sq->size > 0);
    Sq->size--;
}

//指定位置删除
void Erase(SeqList* Sq,int pos)
{
    assert(Sq && pos >= 0 && pos < Sq->size && Sq->size > 0);
    for(int i = pos;i < Sq->size - 1;i++)
    {
        *(Sq->arr + i) = *(Sq->arr + i + 1);
    }
    Sq->size--;
}

//元素个数
size_t Size(SeqList* Sq)
{
    assert(Sq);
    return Sq->size;
}

//空间大小
size_t Capacity(SeqList* Sq)
{
    assert(Sq);
    return Sq->capacity;
}
//打印
void SeqListPrint(SeqList* Sq)
{
    assert(Sq);
    if(!Sq->arr) printf("\n");
    for(int i = 0;i < Sq->size;i++)
    {
        printf("%d ",*(Sq->arr + i));
    }
    printf("\n");
}

//查找元素
size_t Find(SeqList* Sq,int index)
{
    assert(Sq);
    for(int i = 0;i < Sq->size;i++)
    {
        if(index == *(Sq->arr + i))
        {
            return i;
        }
    }
    return -1;
}

//销毁
void Destroy(SeqList* Sq)
{
    assert(Sq);
    if(Sq->arr != NULL)
    {
        free(Sq->arr);
    }
    Sq->arr = NULL;
    Sq->capacity = Sq->size = 0;
}